package com.jw.debezuim.config.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.annotation.Order;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;

@Aspect
@Component
@Slf4j
@Order(Integer.MAX_VALUE-100)
public class AuditLogAspect {

    /**
     * 解析AuditLogPointcut#desc()值中的spel的变量,代表切点方法的入参集合
     */
    public final static String SPEL_VAR_ARGS = "args";
    /**
     * 解析AuditLogPointcut#desc()值中的spel的变量,代表切点方法的返回值
     */
    public final static String SPEL_VAR_RESULT = "result";

    @Autowired
    private ApplicationContext applicationContext;

    @Pointcut(value = "@annotation(AuditLogPointcut)")
    public void pointCut() {
    }

    /**
     * @param jp
     * @return
     * @throws Throwable
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint jp) throws Throwable {

        Object proceed = null;
        AuditLogPointcut AuditLogPointcut = null;
        Object[] args = null;
        try {
            args = jp.getArgs();
            String targetName = jp.getSignature().toString();
            log.info("AuditLogAspect start, menthode[{}]", targetName);
            MethodSignature signature = (MethodSignature) jp.getSignature();
            Method method = jp.getTarget().getClass().getMethod(signature.getName(), signature.getParameterTypes());
            AuditLogPointcut = method.getAnnotation(AuditLogPointcut.class);
        } catch (Throwable e) {
            log.error("AuditLogAspect catch ex", e);
        }

        Collection descResultCol = null;
        if (AuditLogPointcut.preParseDesc()) {
            descResultCol = this.handlerDesc(AuditLogPointcut, args, proceed);
            proceed = jp.proceed();
        } else {
            proceed = jp.proceed();
            descResultCol = this.handlerDesc(AuditLogPointcut, args, proceed);
        }

        try {//切点报错不记录日志
            if (descResultCol != null && !descResultCol.isEmpty()) {
                String remoteIP = this.getRemoteIP();
                Date now = new Date();
                for (Object descResult : descResultCol) {
                    //处理数据
                }
            }
        } catch (Throwable e) {
            log.error("AuditLogAspect catch ex", e);
        }

        return proceed;
    }

    private Collection handlerDesc(AuditLogPointcut AuditLogPointcut, Object[] args, Object proceed) {
        try {
            String[] desc = AuditLogPointcut.desc();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < desc.length; i++) {
                sb.append(desc[i]);
            }
            ExpressionParser spelExpressionParser = new SpelExpressionParser();
            Expression expression = spelExpressionParser.parseExpression(sb.toString());
            StandardEvaluationContext evalContext = new StandardEvaluationContext(args);
            evalContext.setBeanResolver(new BeanFactoryResolver(applicationContext));//设置bean解析器,以支持表达式通过@+bean名称引用bean
            evalContext.setVariable(SPEL_VAR_ARGS, args);//方法参数集合
            evalContext.setVariable(SPEL_VAR_RESULT, proceed);//方法执行结果


            Collection descResultCol = null;
            if (AuditLogPointcut.multi()) {
                descResultCol = expression.getValue(evalContext, Collection.class);
            } else {
                String descResult = expression.getValue(evalContext).toString();
                descResultCol = Arrays.asList(descResult);
            }
            return descResultCol;
        } catch (Throwable e) {
            log.error("AuditLogAspect catch ex", e);
        }
        return null;
    }

    private String getRemoteIP() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request != null){
                String ip = null;
                //X-Forwarded-For：Squid 服务代理
                String ipAddresses = request.getHeader("X-Forwarded-For");
                if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
                    //Proxy-Client-IP：apache 服务代理
                    ipAddresses = request.getHeader("Proxy-Client-IP");
                }
                if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
                    //WL-Proxy-Client-IP：weblogic 服务代理
                    ipAddresses = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
                    //HTTP_CLIENT_IP：有些代理服务器
                    ipAddresses = request.getHeader("HTTP_CLIENT_IP");
                }
                if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
                    //X-Real-IP：nginx服务代理
                    ipAddresses = request.getHeader("X-Real-IP");
                }
                //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
                if (ipAddresses != null && ipAddresses.length() != 0) {
                    ip = ipAddresses.split(",")[0];
                }
                //还是不能获取到，最后再通过request.getRemoteAddr();获取
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
                    ip = request.getRemoteAddr();
                }
                return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
            }
        } catch (Exception e) {
            log.error("获取ip报错", e);
        }
        return "";
    }

}
